
package com.ruhua.java.service;

import com.alibaba.fastjson.JSONObject;
import com.ruhua.java.dao.Goods;
import com.ruhua.java.dao.GoodsSku;
import com.ruhua.java.dao.Sku;
import com.ruhua.java.dto.GoodsDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.GoodsRepository;
import com.ruhua.java.repository.GoodsSkuRepository;
import com.ruhua.java.repository.SkuRepository;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.ruhua.java.util.CommonUtil.toJsonString;
import static com.ruhua.java.util.CommonUtil.toList;


@Service
public class GoodsService {


    Integer i=1;
    Integer j=1;


    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    GoodsSkuRepository goodsSkuRepository;

    @Autowired
    SkuRepository skuRepository;


    public Map<String,Object> addSkuData(Map<String,Object> sku){
        Map<String,Object> json= new HashedMap();
        json.put("tree","123");
        return json;
    }



    public void set_kv_arr(List<Map<String,Object>> skuList)
    {
        ArrayList list=new ArrayList();
        IntStream.range(0,skuList.size()).forEach(k->{
            Map<String,Object> v = skuList.get(k);

            Map<String,Object> oneMap = new HashMap<>();
            v.forEach((vv,kk)->{
            });
        });
    }

    public Long createItem(GoodsDTO dto) {
        try {
            String listString = String.join(",", dto.getBannerimgs());

            Goods item = Goods.builder()
                    .bannerimgs(listString)
                    .goodsName(dto.getGoodsName())
                    .categoryId(dto.getCategory_id())
                    .sales(dto.getSales())
                    .state(dto.getState())
                    .sort(dto.getSort())
                    .stock(dto.getStock())
                    .collects(dto.getCollects())
                    .price(dto.getPrice())
                    .marketPrice(dto.getMarketPrice())
                    .vipPrice(dto.getVipPrice())
                    .imgId(dto.getImg_id())
                    .keywords(dto.getKeywords())
                    .description(dto.getDescription())
                    .content(dto.getContent())
                    .build();
            Goods res_goods=goodsRepository.save(item);
            return res_goods.getGoodsId();
        }catch (Throwable e) {
            System.out.println("创建失败"+e.getMessage());
            throw new NotFoundException(10002);
        }
    }


    public void create_json_sku(long id,List<Map<String,Object>> skuList){
        Map<String,Object> maps = new HashMap<>();
        if(skuList.size()>0) {
            maps.put("tree", this.tree(skuList));
            maps.put("list", this.setList(skuList));
        }else{
            maps=null;
        }
        GoodsSku item = GoodsSku.builder()
                .goodsId(id)
                .json(maps)
                .build();
        goodsSkuRepository.save(item);
    }

    public void create_sku(long id,List<Map<String,Object>> skuList,String goodsname){
        ArrayList<Map> list2=new ArrayList<>();
        IntStream.range(0,skuList.size()).forEach(i->{
            Map<String,Object> m=skuList.get(i);
            List<Object> twolists= m.entrySet().stream().filter(x ->!x.getKey()
                    .equals("stock_num") &&!x.getKey().equals("price")).map(s->{
                return s.getValue();
            }).collect(Collectors.toList());

            System.out.println("twolist:" + toJsonString(twolists));

            String title=twolists.stream().map(n -> String.valueOf(n)).collect(Collectors.joining("-"));
            Sku item = Sku.builder()
                    .price(new BigDecimal(m.get("price").toString()))
                    .stock(Integer.valueOf(m.get("stock_num").toString()))
                    .specs(toJsonString(m))
                    .goodsName(goodsname)
                    .title(title)
                    .goodsId(id)
                    .build();
            skuRepository.save(item);
        });
    }


    public ArrayList<Map> setList(List<Map<String,Object>> skuList){
        ArrayList<Map> list2=new ArrayList<>();
        IntStream.range(0,skuList.size()).forEach(i->{
            Map<String,Object> m=skuList.get(i);
            List<Object> twolists= m.entrySet().stream().filter(x ->!x.getKey()
                    .equals("stock_num") &&!x.getKey().equals("price")).map(s->{
                return s.getValue();
            }).collect(Collectors.toList());
            Map<String,Object> maps = new HashMap<>();
            maps.put("id",i+1);
            maps.put("price",m.get("price"));
            maps.put("stock_num",m.get("stock_num"));
            IntStream.range(0,twolists.size()).forEach(j->{
                Object v = twolists.get(j);
                maps.put("s"+(j+1)+"_name",v);
                Integer mo = i % (j + 1);

                if(j<1) {
                    maps.put("s"+(j+1),100*(j+1) + i);
                }else{
                    maps.put("s"+(j+1),100*(j+1) + mo);
                }
            });
            System.out.println("***************************");
            list2.add(maps);
        });
        return list2;
    }

    public ArrayList<Map> tree(List<Map<String,Object>> skuList){
        ArrayList<Map> treeList=new ArrayList<>();

        Map<String,ArrayList<String>> oneMap = new HashMap<>();
        skuList.forEach(maps->{
            maps.entrySet().stream().filter(x ->!x.getKey().equals("stock_num") &&
                    !x.getKey().equals("price")).forEach(e->{
                String name=e.getKey();
                String value=e.getValue().toString();
                ArrayList<String> xList = new ArrayList<>();
                if(!oneMap.containsKey(name)){
                    xList.add(value);
                    oneMap.put(name,xList);
                }else{
                    oneMap.get(name).add(value);
                }
            });
        });
        oneMap.forEach((k,v)->{
            Map<String,Object> twoMap = new HashMap<>();
            List<Map<String,Object>> vList = new ArrayList<>();

            List<String> vv = v.stream().distinct().collect(Collectors.toList()); IntStream.range(0,vv.size()).forEach(x->{
                Map<String,Object> threeMap = new HashMap<>();
                threeMap.put("id",100*i+x);
                threeMap.put("name",vv.get(x));
                vList.add(threeMap);
            });

            twoMap.put("k",k);
            twoMap.put("v",vList);
            twoMap.put("k_s","s"+ i);
            i++;
            treeList.add(twoMap);
        });
        return treeList;
    }


    public void updateItem(GoodsDTO dto) {
        try {
            String listString = String.join(",", dto.getBannerimgs());
            Goods item = this.getById(dto.getGoodsId());
            item.setBannerimgs(listString);
            item.setGoodsName(dto.getGoodsName());
            item.setCategoryId(dto.getCategory_id());
            item.setSales(dto.getSales());
            item.setState(dto.getState());
            item.setSort(dto.getSort());
            item.setStock(dto.getStock());
            item.setCollects(dto.getCollects());
            item.setPrice(dto.getPrice());
            item.setMarketPrice(dto.getMarketPrice());
            item.setImgId(dto.getImg_id());
            item.setKeywords(dto.getKeywords());
            item.setDescription(dto.getDescription());
            item.setContent(dto.getContent());
            goodsRepository.save(item);
        }catch (Throwable e) {
            System.out.println("更新商品失败"+e.getMessage());
            throw new NotFoundException(10002);
        }
    }


    public Goods getById(Long num) {
        Goods item=goodsRepository.findOneByGoodsId(num);
        System.out.println("goods:"+item+"num:"+num);
        return item;
    }

    public String getProPic(Long id) {
        Optional<Goods> opItem=goodsRepository.findById(id);
        Goods item=opItem.orElseThrow(()->new TrowException("商品不存在"));
        String pics=item.getBannerimgs();
        String[] picArray=pics.split(",");
        String res="";
        if(picArray.length>0){
            res=picArray[0];
        }
        return res;
    }


    public List<Goods> findByNames(List<String> names){
        return goodsRepository.findByNames(names);
    }

    public List<Goods> getGoodsList() {
        return this.goodsRepository.findAll();
    }



    public Page<Goods> getGoodsListPages(Integer pageNum, Integer size) {
        Pageable page = PageRequest.of(pageNum,size, Sort.by("id").descending());
        return this.goodsRepository.findAll(page); }

    public void UpGoodFiled(Long id,String field){
        Goods item=this.getById(id);
        if(item == null){
            throw new NotFoundException(10003);
        }
        switch (field) {
            case "is_recommend":
                if(item.getIsRecommend()==1){
                    item.setIsRecommend(0);
                }else{
                    item.setIsRecommend(1);
                }
                break;
            case "is_hot":
                if(item.getIsHot()==1){
                    item.setIsHot(0);
                }else{
                    item.setIsHot(1);
                }
                break;
            case "is_new":
                if(item.getIsNew()==1){
                    item.setIsNew(0);
                }else{
                    item.setIsNew(1);
                }
                break;
            case "state":
                if(item.getState()==1){
                    item.setState(0);
                }else{
                    item.setState(1);
                }
                break;
            default:
                throw new NotFoundException(10003);
        }
        goodsRepository.save(item);
    }

    public List<GoodsSku> getSkuListByIds(List<Long> ids) {
        return this.goodsSkuRepository.findAllBySkuIdIn(ids);
    }
}
